import "./relationProcess.css";
import clsx from "clsx";
import { useForm } from "../../framework/common/context/metadata-context";
import { Tooltip, Spin} from 'antd';
import EditRelationProcess from "./EditRelationProcess1";
import { useRef, useState } from "react";
import eventBus, { useSubscribe } from "../../framework/common/eventBus";
import { openReationProcess } from "./utility";
import useOperationConnect from "../../framework/common/lifecycle/useOperationConnect";
import { useUpdate } from "ahooks";
export default function(){
    const { data: tplData, urlPrefix, mode} = useForm().root;
    const updater = useUpdate()

    useSubscribe("relation.update",()=>{
        updater()
    })
    if(!tplData.RelationProcess){
        console.log('缺少tp.RelationProcess，不显示相关流程');
        return null
    }
    // tplData.RelationProcess.CanView =1//测试数据
    // tplData.RelationProcess.CanEdit = 1;//测试数据
    // tplData.RelationProcess.Required = true;//测试数据
    if(tplData.RelationProcess.CanView === 0){
        return null;
    }

    //打印隐藏
    if (tplData?.hideInfo?.deteleRelationGroup===true) {
        return null
    }

    return <RelationProcess></RelationProcess>

}

function RelationProcess({}){
    const { data: tplData, urlPrefix, mode} = useForm().root;
    let domRef=useRef()
    let headerRef=useRef()
    let canEdit = tplData.RelationProcess.CanEdit === 1;//是否编辑关联流程 1可编辑  0不可编辑，
    if(mode === "Print"){
        canEdit = false;//打印模式强制不可编辑
    }
    const [relationProcessList, setRelationProcessList] = useState(tplData.RelationProcess.RelationProcessList || []);//已选的关联流程列表
    const [validaState, setValidaState] = useState(false);//是否显示校验状态
    
    // if(!canEdit && relationProcessList.length<=0){//不可关联流程，并且无数据，直接返回null
    //     return null
    // }

    //更新状态以及tplData
    function updataTpldata(list){
        setRelationProcessList(list);//追加选中的流程到列表展示
        tplData.RelationProcess.RelationProcessList = list;//更新tplData内的关联流程数据
    }



    //监听关联流程更新
    useSubscribe("relationProcessList.update", (data)=>{
        updataTpldata(data);
    });

    //监听关联流程更新
    useSubscribe("validaRelation.update", (data)=>{
        setValidaState(true);
    });

    //新增关联流程
    function addRows(selectrows){
        updataTpldata(relationProcessList.concat(selectrows));//更新
    }

    //删除关联流程
    function deleteRow(proc_id){
        let newList =  relationProcessList.filter(function(item){
            return item.proc_id !== proc_id;
        });//过滤当前删除的流程
        updataTpldata(newList);//更新
    }
    let errorClassName = "";
    if(relationProcessList.length <= 0 && validaState && tplData.RelationProcess.Required === true){//如果没数据，且触发了校验，相关流程显示标红
        errorClassName = "hasError";
    }
    const operationConnector = useOperationConnect(
        () => headerRef.current?.getBoundingClientRect(),
        () => domRef.current?.getBoundingClientRect(),
        {
            type: "relation-header",
          }
    );

    //打印模式，如果所有Item被删除，就隐藏整个相关流程
    if(mode==="Print"&&relationProcessList?.length>0 &&  (relationProcessList?.length===tplData?.hideInfo?.detele_relation_arr?.length)){
        return null;
    }
    return <>
        <div  ref={domRef} className="relationProcess">
            <div ref={headerRef} {...operationConnector} className="rp_wrap print-border-color print-border-1px print-border-b-none">
                <span className="rp_title text-sm">相关流程
                    {
                        tplData.RelationProcess.Required === true
                        && <span className="text-red align-middle"> *</span>
                    }
                </span>
                {
                    canEdit//可编辑，显示新增按钮
                    && <EditRelationProcess 
                        relationProcessList={relationProcessList}
                        urlPrefix={urlPrefix}
                        handleOk={(selectrows)=>{
                            addRows(selectrows)
                        }}></EditRelationProcess>
                }
            </div>
            <div className={clsx('relation_process_wrap print-border-color', errorClassName)}>
                {
                    relationProcessList.length > 0
                    ? <ul className="mb-0">
                        {
                            relationProcessList.map(function(item, ind){
                                return <RelationProcessItem key={item.proc_id} canEdit={canEdit} item={item} ind={ind} deleteRow={deleteRow}></RelationProcessItem>
                            })
                        }
                    </ul>
                    : <div className="no_relation_process text-sm">无相关流程</div>
                }
            </div>
        </div>
    </>
}

function RelationProcessItem({item,ind,canEdit,deleteRow}){
    const { data: tplData, mode} = useForm().root;
    const itemRef= useRef()
    const operationConnector = useOperationConnect(
        () => itemRef.current?.getBoundingClientRect(),
        () => itemRef.current?.getBoundingClientRect(),
        {
            type: "relation-item",
            id:item.proc_id
        }
      );

      //打印隐藏
    if(Array.isArray(tplData?.hideInfo?.detele_relation_arr)){
        if(tplData?.hideInfo?.detele_relation_arr.includes(item?.proc_id)){
            return null
        }
    }

    return <li {...operationConnector} ref={itemRef}  className="process_item_wrap text-sm">
    {
        mode === "Print"
        && item.name
    }
    {
        mode !== "Print"
        && <Tooltip overlayClassName="mytip"
                color="white"
                overlayStyle={{"maxWidth": "760px"}} placement="bottomLeft" title={item.name}
            >
                <RelationProcessLink
                    href={item.url_pc}
                    text={item.name}
                >
                </RelationProcessLink>
                {
                    canEdit//可编辑，显示删除按钮
                    && <span className="cursor-pointer delete_process" onClick={()=>{deleteRow(item.proc_id)}} data-index={ind}><i className="text-xs iconfont icon-guanbi1"></i>  </span>
                }
            </Tooltip>
    }
</li>
}

//关联流程超链接
function RelationProcessLink({
    href,
    text
  }){
  
    const [spinState, setSpinState] = useState(false);
  
    return <Spin
              spinning={spinState}
            >
              <a 
                className="cursor-pointer process_item"
                data-title={text}
                onClick={()=>{
                    setSpinState(true);
                    openReationProcess({url: href}).then(function(){
                        setSpinState(false);
                    }).catch(function(){
                        setSpinState(false);
                    })
                }}>
                    <i className="iconfont icon-xiangguanliucheng"></i>{text}
                </a>
            </Spin>
  }

//校验关联流程
export function validarelationProcessList({
    tplData
}){
    let otherError = {
        code: 0,
        message: ""
    };
    if(
        tplData.RelationProcess.Required === true //关联流程必填
        && tplData.RelationProcess.RelationProcessList.length <=0 //没有选择关联流程
        && tplData.RelationProcess.CanView == 1 //关联流程显示了
        && tplData.RelationProcess.CanEdit == 1 //关联流程可编辑
    ){
        eventBus.publish("validaRelation.update", true);//显示关联流程必填 
        otherError = {
            code: 1,
            message: "请关联流程"
        }
    }
    return otherError;
}